<?php
	class Sss_Ultility_Common {
		/**
		* Get number
		* 
		* @param string $number
		* @param string $precision
		*/
		public function getNumber($number, $precision)
		{
			$locale = new Zend_Locale(LOCATE);
			//If check number
			if(is_numeric($precision)){
				$nPrecision = (integer)$precision;
				$number = Zend_Locale_Format::getNumber($number,
				array('locale' => $locale,
				'precision' => $nPrecision)
				); 
			} else {
				$number = Zend_Locale_Format::getNumber($number,
				array('locale' => $locale, 
				'number_format' => $precision)
				);
			}
			return $number;
		}
		/**
		* To number
		* 
		* @param string $number
		* @param string $precision
		*/
		public function toNumber($number,$precision)
		{
			$locale = new Zend_Locale(LOCATE);
			//Check null or empty
			if($precision == null || $precision == "") {
				$number = Zend_Locale_Format::toNumber($number,
				array('locale' => $locale)
				); 
			}
			//If check is number
			else if(is_numeric($precision)) {
					$nPrecision = (integer)$precision;
					$number = Zend_Locale_Format::toNumber($number,
					array('locale' => $locale,
					'precision' => $nPrecision)
					); 
				} else {
					$number = Zend_Locale_Format::toNumber($number,
					array('locale' => $locale,
					'number_format' => $precision)
					); 
			} 
			return $number;
		}
		/**
		* Is number
		* 
		* @param string $number
		*/
		public function isNumber($number) 
		{
			$locale = new Zend_Locale(LOCATE);
			if (Zend_Locale_Format::isNumber($number, array('locale' => $locale))) {
				//return const number if true else return notnumber if false
				return "number";
			} else {
				return "notnumber";
			}
		}
		/**
		* Get float
		* 
		* $param string $fnumber
		* $param integer $precision
		*/
		public function getFloat($fnumber, $precision)
		{
			$locale = new Zend_Locale(LOCATE);
			$number = Zend_Locale_Format::getFloat($fnumber,
			array('precision' => $precision,
			'locale' => $locale)
			);
			return $number;
		}
		/**
		* To float
		* 
		* $param string $fnumber
		* $param integer $precision
		*/
		public function toFloat($fnumber, $precision)
		{
			$locale = new Zend_Locale(LOCATE);
			$number = Zend_Locale_Format::toFloat($fnumber,
			array('precision' => $precision,
			'locale' => $locale)
			);
			return $number;
		}
		/**
		* Is float
		* 
		* $param string $fnumber
		*/
		public function isFloat($fnumber)
		{
			$locale = new Zend_Locale(LOCATE);
			if (Zend_Locale_Format::isFloat($fnumber, array('locale' => $locale))) {
				//return const float if true else return const notfloat if false
				print "float";
			} else {
				print "notfloat";
			} 
		}
		/**
		* Get integer
		* 
		* @param string $inumber
		*/
		public function getInteger($inumber)
		{
			$locale = new Zend_Locale(LOCATE);
			$number = Zend_Locale_Format::getInteger($inumber,
			array('locale' => $locale)
			);
			return $number;
		}
		/**
		* To integer
		* @param string $inumber
		*/
		public function toInteger($inumber)
		{
			$locale = new Zend_Locale(LOCATE);
			$number = Zend_Locale_Format::toInteger($inumber,
			array('locale' => $locale)
			);
			return $number;
		}
		/**
		* Is integer
		* 
		* @param string $inumber
		*/
		public function isInteger($inumber)
		{
			$locale = new Zend_Locale(LOCATE);
			if (Zend_Locale_Format::isInteger($inumber, array('locale' => $locale))) {
				//return const integer if true else return const notinteger if false
				print "integer";
			} else {
				print "notinteger";
			}
		}
		/**
		* put your comment there...
		* 
		* @param string $dateTime
		* @param string $timeZone
		* @return string
		*/
		public function getTimeZone($dateTime,$timeZone)
		{
			$date = new Zend_Date($dateTime, Zend_Date::DATES, 'de');

			// set another timezone
			$date->setTimezone($timeZone);

			// what timezone do we now have
			$iso = $date->getIso();
			$startAdd = strpos($iso,'+');
			$startSub = strpos($iso,'-');

			$strIso =  substr($iso,$startAdd,strlen($iso)-$startAdd - 3);
			if($strIso == "" || $strIso == null)
				$strIso = substr($iso,$startSub,strlen($iso)-$startSub - 3);

			return $strIso;
		}
		/**
		* put your comment there...
		* 
		* @param string $dateTime
		* @param string $dateFormat
		* @return string
		*/
		public function getDateTime($dateFormat, $dateTime)
		{
			if(is_numeric($dateTime)) {
				$dateTime = (integer)$dateTime;
			} else {
				return;
			}

			$dateZone = gmdate($dateFormat,$dateTime);

			$date = new Zend_Date($dateZone, Zend_Date::DATES, 'de');

			// set another timezone
			$date->setTimezone(CONFIGTIMEZONE);

			// what timezone do we now have
			$iso = $date->getIso();

			$startAdd = strpos($iso,'+');
			$startSub = strpos($iso,'-');
			$strIso =  substr($iso,$startAdd,strlen($iso)-$startAdd - 3);
			if($strIso == "" || $strIso == null)
				$strIso = substr($iso,$startSub,strlen($iso)-$startSub - 3);

			$timeZone = $strIso;
			return gmdate($dateFormat,$dateTime + ($timeZone * 3600));
		}
		/**
		* put your comment there...
		* 
		*/
		public function getDateTimeNumber($dateTime = null)
		{
			if($dateTime != null) {
				$date = new Zend_Date($dateTime, DATETIMEFORMATZENDDATE);
			} else {
				$date = new Zend_Date();
			}
			return $date->get();
		}
		public static function getDistanceDateTime($fromDateTime, $toDateTime, $lngh) 
		{
			$tm = $fromDateTime;
			$cur_tm = $toDateTime; $dif = $cur_tm-$tm;
			$pds = array('minute_number', 'hour_number', 'day_number', 'week_number', 'month_number', 'year_number');
			for($v = sizeof($lngh)-1; ($v >= 0)&&(($dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $cur_tm-($dif%$lngh[$v]);
			return $pds[$v];
		}

		public static function getDistanceDate($startDate, $endDate)
		{
			$startDate = date(DATEFORMAT, strtotime($startDate));
			$endDate = date(DATEFORMAT, strtotime($endDate));
			return round((strtotime($endDate) - strtotime($startDate)) / 86400, 0);
		}
		public function genRandomString($length = 10) 
		{
			$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
			$string = '';    
			for ($p = 0; $p < $length; $p++) {
				$string .= $characters[mt_rand(0, strlen($characters) -1)];
			}
			return $string;
		}
		public function genRandomColor($length = 6)
		{
			$characters = '0123456789abc';
			$string = '';
			for ($p = 0; $p < $length; $p++) {
				$string .= $characters[mt_rand(0, strlen($characters) -1)];
			}
			return $string;
		}
		public function dropDatabase($newDBName)
		{
			try {
				$config     = Zend_Controller_Front::getInstance()
				->getParam('bootstrap')->getOptions();

				// Connect to server my sql
				mysql_connect ($config['resources']['db']['params']['host'], $config['resources']['db']['params']['username'], $config['resources']['db']['params']['password']);

				// Drop new database with instance created
				mysql_query("DROP DATABASE $newDBName");
			} catch (Exception $e) {
				Sss_Ultility_Common::logger()->log($e, Zend_Log::ERR);
			}
		}
		public function generateDatabase($newDBName)
		{
			try { 
				$config     = Zend_Controller_Front::getInstance()
				->getParam('bootstrap')->getOptions();

				// Connect to server my sql
				mysql_connect ($config['resources']['db']['params']['host'], $config['resources']['db']['params']['username'], $config['resources']['db']['params']['password']);

				// Create new database with instance created
				mysql_query("CREATE DATABASE $newDBName");

				// Select database
				mysql_select_db("$newDBName");

				// Temporary variable, used to store current query
				$templine = '';

				if($filename == null)
					$filename = 'shepherd.sql';

				// Read in entire file
				$lines = file($filename);

				// Loop through each line
				foreach ($lines as $line)
				{
					// Skip it if it's a comment
					if (substr($line, 0, 2) == '--' || $line == '')
						continue;

					// Add this line to the current segment
					$templine .= $line;

					// If it has a semicolon at the end, it's the end of the query
					if (substr(trim($line), -1, 1) == ';')
					{
						// Perform the query
						mysql_query($templine);

						// Reset temp variable to empty
						$templine = '';
					}
				}
			} catch (Exception $e) {
				Sss_Ultility_Common::logger()->log($e, Zend_Log::ERR);
			}
		}
		public function sendMail($mailFrom, $mailTo, $subject, $body)
		{
			$to = $mailTo;
			//$headers = "From: $mailFrom";
			$headers .= "Reply-To: OVIS Telematics <$mailFrom>\r\n";
			$headers .= "Return-Path: OVIS Telematics <$mailFrom>\r\n";
			$headers .= "From: OVIS Telematics <$mailFrom>\r\n"; 
			$headers .= "Organization: OVIS Telematics\r\n";
			$headers .= "MIME-Version: 1.0\r\n";
			$headers .= "Content-type: text/plain; charset=utf-8\r\n";
			$headers .= "X-Priority: 3\r\n";
			$headers .= "X-Mailer: PHP". phpversion() ."\r\n"; 
			$isSend = mail($to,$subject,$body,$headers);
			return $isSend;
		}
		public function in_array_field($needle, $needle1, $needle_field, $needle_field1, $haystack, $strict = false) { 
			if ($strict) { 
				foreach ($haystack as $item) 
					if (isset($item[$needle_field]) && $item[$needle_field] === $needle &&
					isset($item[$needle_field1]) && $item[$needle_field1] === $needle1) 
						return 1; 
			}
			return 0; 
		}
		public function dataHistory($note, $hardwareId, $create_by) 
		{
			$history = new Application_Model_History();
			$history->setHistoryType(Sss_Ultility_Setting::HISTORY_TYPE_HARDWARE);
			$history->setModifiedDate(Sss_Ultility_Common::getDateTimeNumber());
			$history->setCreatedBy($create_by);
			$history->setHardware($hardwareId);
			$history->setNote($note);
			return $history;
		}
		public function defaultListRoleAdministrator()
		{
			return array(
			0 => array(
			'feature' => Sss_Ultility_CommonViewParamater::PER_FlOOR_PLAN,
			'action' => Sss_Ultility_CommonViewParamater::SELECT),
			1 => array(
			'feature' => Sss_Ultility_CommonViewParamater::PER_FlOOR_PLAN,
			'action' => Sss_Ultility_CommonViewParamater::EDIT),
			2 => array(
			'feature' => Sss_Ultility_CommonViewParamater::PER_DYNAMIC_MONITORING,
			'action' => Sss_Ultility_CommonViewParamater::ALL),
			3 => array( 
			'feature' => Sss_Ultility_CommonViewParamater::PER_GRAPHS,
			'action' => Sss_Ultility_CommonViewParamater::ALL),
			4 => array(
			'feature' => Sss_Ultility_CommonViewParamater::PER_GEOMAPPING,
			'action' => Sss_Ultility_CommonViewParamater::ALL),
			5 => array(
			'feature' => Sss_Ultility_CommonViewParamater::PER_CONFIGURATION,
			'action' => Sss_Ultility_CommonViewParamater::ALL),
			6 => array(
			'feature' => Sss_Ultility_CommonViewParamater::PER_STOCK_LOCATION,
			'action' => Sss_Ultility_CommonViewParamater::ADD),
			7 => array(
			'feature' => Sss_Ultility_CommonViewParamater::PER_STOCK_LOCATION,
			'action' => Sss_Ultility_CommonViewParamater::EDIT),
			8 => array(
			'feature' => Sss_Ultility_CommonViewParamater::PER_STOCK_LOCATION,
			'action' => Sss_Ultility_CommonViewParamater::DELETE),
			9 => array(
			'feature' => Sss_Ultility_CommonViewParamater::PER_SHIPMENT,
			'action' => Sss_Ultility_CommonViewParamater::ADD),
			10 => array(
			'feature' => Sss_Ultility_CommonViewParamater::PER_SHIPMENT,
			'action' => Sss_Ultility_CommonViewParamater::EDIT),
			11 => array(
			'feature' => Sss_Ultility_CommonViewParamater::PER_SHIPMENT,
			'action' => Sss_Ultility_CommonViewParamater::DELETE),
			12 => array(
			'feature' => Sss_Ultility_CommonViewParamater::PER_RMA,
			'action' => Sss_Ultility_CommonViewParamater::ALL),
			13 => array(
			'feature' => Sss_Ultility_CommonViewParamater::PER_ANALYSIS,
			'action' => Sss_Ultility_CommonViewParamater::ALL),
			14 => array(
			'feature' => Sss_Ultility_CommonViewParamater::PER_SUPPORT_OTRS,
			'action' => Sss_Ultility_CommonViewParamater::ALL),
			15 => array(
			'feature' => Sss_Ultility_CommonViewParamater::PER_SUPPORT_MANUALS,
			'action' => Sss_Ultility_CommonViewParamater::ALL),
			16 => array(
			'feature' => Sss_Ultility_CommonViewParamater::PER_SUPPORT_SLA,
			'action' => Sss_Ultility_CommonViewParamater::ALL),
			17 => array(
			'feature' => Sss_Ultility_CommonViewParamater::PER_STOCK_LOCATION,
			'action' => Sss_Ultility_CommonViewParamater::VISIBLE),
			18 => array(
			'feature' => Sss_Ultility_CommonViewParamater::PER_SHIPMENT,
			'action' => Sss_Ultility_CommonViewParamater::VISIBLE),
			19 => array(
			'feature' => Sss_Ultility_CommonViewParamater::PER_MY_HARDWARE,
			'action' => Sss_Ultility_CommonViewParamater::ALL)
			);
		}

		function selfURL()
		{ 
			if (!isset($_SERVER['REQUEST_URI'])) 
			{ 
				$serverrequri = $_SERVER['PHP_SELF']; 
			} else{ 
				$serverrequri = $_SERVER['REQUEST_URI']; 
			} 
			$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
			$s1 = strtolower($_SERVER["SERVER_PROTOCOL"]);
			$s2 = "/";
			$protocol = substr($s1, 0, strpos($s1, $s2)).$s; 
			$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]); 
			return $protocol."://".$_SERVER['SERVER_NAME'].$port.$serverrequri; 
		}

		function getCurrDomain()
		{
			$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
			$s1 = strtolower($_SERVER["SERVER_PROTOCOL"]);
			$s2 = "/";
			$protocol = substr($s1, 0, strpos($s1, $s2)).$s; 
			$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]); 
			return $protocol."://".$_SERVER['SERVER_NAME'].$port;
		}

		function downloadFile($path)
		{
			$fullPath = $_SERVER['DOCUMENT_ROOT'].$path;
			if ($fd = fopen ($fullPath, "r")) {
				$fsize = filesize($fullPath);
				$path_parts = pathinfo($fullPath);
				$ext = strtolower($path_parts["extension"]);
				header('Content-Description: File Transfer');
				header('Content-Type: application/force-download');
				switch ($ext) {
					case "pdf":
						header("Content-type: application/pdf"); // add here more headers for diff. extensions
						header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
						break;
					default;
						header("Content-type: application/octet-stream");
						header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
				}
				header("Content-length: $fsize");
				header("Cache-control: private"); //use this to open files directly
				while(!feof($fd)) {
					$buffer = fread($fd, 2048);
					echo $buffer;
				}
			}
			fclose ($fd); 
			exit;
		}
		function importData($createdBy, $csvfile = null, $databasetable = null)
		{

			$databasetable = "hardware";
			$fieldseparator = ",";
			$lineseparator = "\n";
			/********************************************************************************************/
			if(!file_exists($csvfile)) {
			}

			$file = fopen($csvfile,"r");
			if(!$file) {
			}

			$size = filesize($csvfile);
			if(!$size) {
			}

			$csvcontent = fread($file,$size);
			fclose($file);

			$lines = 0;
			$hardwareIds = null;
			$linearray = array();
			$status = Sss_Ultility_Setting::HARDWARE_STATUS_INACTIVE;
			$createdDate = Sss_Ultility_Common::getDateTimeNumber();
			foreach(explode($lineseparator,$csvcontent) as $line) {

				$lines++;
				$line = trim($line," \t");
				$line = str_replace("\r","",$line);

				/************************************************************************************************************
				This line escapes the special character. remove it if entries are already escaped in the csv file
				************************************************************************************************************/
				$line = str_replace("'","\'",$line);
				/***********************************************************************************************************/

				$linearray = explode($fieldseparator,$line);
				$linemysql = implode("','",$linearray);
				$query = null;
				$queries = null;
				if($linemysql != ''){
					if(strlen($linemysql) >= 5){
						//sub string typecode compare and get hardware type
						$typeCode = substr($linemysql,0,5);

						//create new table system type
						$systemTypeTable = new Application_Model_Mapper_SystemType();

						//get hardware type by typecode
						$systemType = $systemTypeTable->getSystemByTypeCode(trim($typeCode));
						if(isset($systemType->systemtypeid)){
							$hardwareType = $systemType->systemtypeid;
						}
						else{
							$hardwareType = null;
						}
						//check serial number of hardware existed on table hardware
						$hardwareTable = new Application_Model_Mapper_Hardware();
						$hardwareContructor = new Application_Model_Hardware();
						$hardware = $hardwareTable->checkExistBySerialNumber(trim($linemysql));
						//check hardware type after insert data to database
						if($hardware == false){
							$hardwareContructor->setSerialNumber($linemysql);
							$hardwareContructor->setCreatedDate($createdDate);
							$hardwareContructor->setCreatedBy($createdBy);
							$hardwareContructor->setUpdatedDate($createdDate);
							$hardwareContructor->setUpdatedBy($createdBy);
							$hardwareContructor->setStatus($status);
							$hardwareContructor->setHardwaretype($hardwareType);
							$hardwareContructor->setAllocation(Resources::_('NOT_ALLOCATED'));
							$hardwareContructor->setRmaType(Sss_Ultility_Setting::RMA_TYPE_DEFAULT);
							$hardwareContructor->setRmaStatus(Sss_Ultility_Setting::RMA_STATUS_OPEN);
							$hardwareId = $hardwareTable->save($hardwareContructor);
							if(isset($hardwareId)){
								if($hardwareIds != null){
									$hardwareIds = $hardwareIds.',';
								}
								$hardwareIds = $hardwareIds.$hardwareId;
							}
						}
					}
				}
			}
			return $hardwareIds;
		}

		function logger($type = null)
		{
			//Get folder and file default
			$folderLog = FOLDER_LOG;
			$fileLogActive = FILE_LOG_ACTIVE;

			//Check folder or file not exist is create the new folder or file
			if($fileLogActive == "" || !$fileLogActive || $type == null){
				$fileLogActive = "error-log.txt";
			}
			if($type == Sss_Ultility_Setting::CHECK_CREATE_LOG_CHART) {
				$fileLogActive = "checkTime.txt";
			}
			if($folderLog == "" || !$folderLog || !is_dir($folderLog)){
				//Desired folder structure
				$folderDefault = "logs";
				if(!is_dir($folderDefault)){
					if (!mkdir($folderDefault, 0, true)) {
						echo 'logs';die;
					}
				}
				$folderLog = $folderDefault;
			}

			//Get logger of Zend Framework
			$logger = new Zend_Log();
			$fileName = "$folderLog/$fileLogActive";
			//Create file if it not exist
			if(!$fileName){
				fopen($fileName, "w+");
			}

			//Get size of file
			if($fileName){
				$size = @filesize($fileName);
			}
			else{
				$size = 0; 
			}

			//Create new filename with format date
			$date = date("m-d-Y H:i:j");
			$date = str_replace(' ','-',$date);
			$date = str_replace(':','-',$date);

			//Check size of file with max value config in Index PHP file
			if($size >= MAX_SIZE_LOG){
				rename("$folderLog/$fileLogActive", "$folderLog/error-log.$date.txt");
				$fileName =  "$folderLog/$fileLogActive";
				fopen($fileName, "w+");
			}
			//Writer log for ZF
			$writer = new Zend_Log_Writer_Stream($fileName);
			$logger->addWriter($writer);

			//Rerurn logger;
			return $logger;
		}

		function loggerPostData()
		{
			//Get folder and file default
			$folderLog = FOLDER_LOG;
			$fileLogActive = FILE_LOG_POST_ACTIVE;

			//Check folder or file not exist is create the neu folder or file
			if($fileLogActive == "" || !$fileLogActive){
				$fileLogActive = "error-log-post-data.txt";
			}
			if($folderLog == "" || !$folderLog || !is_dir($folderLog)){
				//Desired folder structure
				$folderDefault = "logs";
				if(!is_dir($folderDefault)){
					if (!mkdir($folderDefault, 0, true)) {
						echo 'logs';die;
					}
				}
				$folderLog = $folderDefault;
			}

			//Get logger of Zend Framework
			$logger = new Zend_Log();
			$fileName = "$folderLog/$fileLogActive";
			//Create file if it not exist
			if(!$fileName){
				fopen($fileName, "w+");
			}

			//Get size of file
			if($fileName){
				$size = @filesize($fileName);
			}
			else{
				$size = 0; 
			}

			//Create new filename with format date
			$date = date("m-d-Y H:i:j");
			$date = str_replace(' ','-',$date);
			$date = str_replace(':','-',$date);

			//Check size of file with max value config in Index PHP file
			if($size >= MAX_SIZE_LOG){
				rename("$folderLog/$fileLogActive", "$folderLog/error-log-post-data.$date.txt");
				$fileName =  "$folderLog/$fileLogActive";
				fopen($fileName, "w+");
			}
			//Writer log for ZF
			$writer = new Zend_Log_Writer_Stream($fileName);
			$logger->addWriter($writer);

			//Rerurn logger;
			return $logger;
		}
		function formatString($number, $format)
		{
			while (strlen($number) < $format) $number = "0".$number;
			return   $number;
		}
		public function showArray($ob)
		{
			echo '<pre>';
			print_r($ob);
			echo '</pre>';
		}
		public static function uploadFiles( $uploadFiles , $options = array() )
		{
			if( !is_array($options) 
			&& empty($options)
			|| empty($options['fullPath'])
			|| empty($options['fullUrl'])
			)
				return array();

			$files = array();
			foreach($uploadFiles as &$val)
			{
				$val = is_array($val)?$val:array($val);
			}
			foreach($uploadFiles['tmp_name'] as $i=>$tmp_file)
			{
				$j = 1;
				$fileName = $uploadFiles['name'][$i];
				while(is_file($options['fullPath'].$fileName))
				{

					$fileName = preg_replace('/(.*)\.(.*)$/','$1-' . $j . '.$2',$uploadFiles['name'][$i]);
					$j++;
				}
				if(move_uploaded_file($tmp_file,$options['fullPath'].$fileName))
				{
					chmod($options['fullPath'].$fileName,0777);
					$info     = getimagesize($options['fullPath'].$fileName);
					$files[]  = array(
					'name'        => $fileName,
					'fullPath'    => $options['fullPath'].$fileName,
					'fullUrl'     => $options['fullUrl'].$fileName,
					'width'		  => $info[0], 
					'height'	  => $info[1],
					'mine'		  => $info['mime']
					);
				}
			}
			return  $files;
		}
		public function defaultListColorInGraph(){
			$arrGraph = array();
			$arrGraph[] = '#75DA6C';
			$arrGraph[] = '#E80808';
			$arrGraph[] = '#0927E7';
			$arrGraph[] = '#C4E61A';
			$arrGraph[] = '#586E98';
			$arrGraph[] = '#0CB9E4';//
			$arrGraph[] = '#434543';
			$arrGraph[] = '#D2A52A';
			return $arrGraph;
		}
		/*
		* Start function convertCoordinatesToPixels
		* */
		public function convertCoordinatesToPixels()
		{
			$checkexits = file_exists(APPLICATION_PATH."/../library/Sss/Ultility/LocalizationConfigurationFloorplan.php");
			if($checkexits)
			{
				$arr = Sss_Ultility_LocalizationConfigurationFloorplan::configfloorplan();
				try
				{
					foreach($arr as $arrfl)
					{
						$idfloorplan = $arrfl[Sss_Ultility_CommonViewParamater::FLOOR_PLAN_ID];
						$coorblue = explode(",",$arrfl[Sss_Ultility_CommonViewParamater::NODE_FLOORPLAN_COORDINATES]);//Blue point
						$coorgreen = explode(",",$arrfl[Sss_Ultility_CommonViewParamater::FIXED_NODE_COORDINATES]);// Green point
						$coorunit = explode(",",$arrfl[Sss_Ultility_CommonViewParamater::FIXED_NODE_RELATIVE_COORDINATES]);
						$coorfixnode = explode(",",$arrfl[Sss_Ultility_CommonViewParamater::FIXED_NODE_RELATIVE_COORDINATES]);
						$noderelativecoor = explode(",",$arrfl[Sss_Ultility_CommonViewParamater::NODE_FLOORPLAN_RELATIVE_COORDINATES]);
						if ( !is_numeric($noderelativecoor[0]) || !is_numeric($noderelativecoor[1]) || !is_numeric($coorblue[0]) || !is_numeric($coorblue[1]) || !is_numeric($coorgreen[0]) || !is_numeric($coorgreen[1]) || is_numeric($coorfixnode[0] || is_numeric($coorfixnode[1]))) {
							return array();
						}
						$coormidx = abs($coorblue[0] - $coorgreen[0]);
						$coormidy = abs($coorblue[1] - $coorgreen[1]);
						$howpixelx =(abs($coorunit[0]-$noderelativecoor[0]))/$coormidx;
						$howpixely = (abs($coorunit[1]-$noderelativecoor[1]))/$coormidy;
						$pixelunit = $howpixelx.",".$howpixely;
						$resultunit[$idfloorplan] = $pixelunit;

					}
					return $resultunit;

				}catch(Exception $e){
					echo $e;
				}
			}else{
				return array();
			}
		}
		//End
		/*
		* Start function check status hardware
		* */
		public function checkHardwareOnline($dayMax)
		{
			$now = date(DATETIME_MYSQL_FORMAT);
			$today = strtotime($now);
			$convertDate = strtotime($dayMax);
			if(($today - $convertDate) <= TIMER_ONLINE){ 
				return true;
			}
			return false;
		}

		public function checkHardwareOfline($dayMax)
		{
			$now = date(DATETIME_MYSQL_FORMAT);
			$today = strtotime($now);
			$convertDate = strtotime($dayMax);
			if(($today - $convertDate) >= SENSOR_OFFLINE_TIME){
				return true;
			}
			return false;
		}

		public function checkHardwareBadConnection($hardwareId,$vendor,$typeCode)
		{

			if($vendor == "2"){ 
				$end = date(DATETIME_MYSQL_FORMAT);
				$start = date(DATETIME_MYSQL_FORMAT, mktime(date("H")-2));
				$lemdataTable = new Application_Model_Mapper_LEMData();
				$dataHardware = $lemdataTable->getHardwareLemDataFromToLemData($hardwareId, $start, $end,$typeCode);
				for ($i = 0; $i < count($dataHardware); $i++)
				{
					$beginItem = $dataHardware[$i]['ec_timestamp'];
					$afterItem = $dataHardware[$i+1]['ec_timestamp'];
					$convertTimeBegin = strtotime($beginItem);
					$convertTimeAfter = strtotime($afterItem);
					$convertEnd = strtotime($end);
					if(($convertEnd-strtotime($dataHardware[count($dataHardware) - 1]['ec_timestamp'])) >= SENSOR_BAD_CONNECTION_INTERVAL ) {
						return true;
					} elseif(( $convertTimeAfter - $convertTimeBegin ) >= SENSOR_BAD_CONNECTION_INTERVAL) {
						return true;
					}
				}
			}else{
				$today = strtotime('now');
				$start = $today - TIMER_BAD_CONNECTION;
				$postdataTable = new Shepherd_Model_Mapper_PostData();
				$dataHardware = $postdataTable->getHardwarePostDataFromToPostData($hardwareId, $start, $today,$typeCode);
				for ($i = 0; $i < count($dataHardware); $i++)
				{
					if(($today - ($dataHardware[count($dataHardware) - 1]['created_date'])) >= SENSOR_BAD_CONNECTION_INTERVAL ) {
						return true;
					} else if(($dataHardware[$i+1]['created_date'] - $dataHardware[$i]['created_date']) >= SENSOR_BAD_CONNECTION_INTERVAL) {
						return true;
					}
				}
			}
			return false;
		}
		//End

		/**
		* Add auto hardware
		*
		* @param
		*/
		public function autoAddHardware($serial,$allocation,$stockLocation)
		{
			$hardwareTable = new Application_Model_Mapper_Hardware();
			$hardwareContructor = new Application_Model_Hardware();
			$hardwareContructor->setSerialNumber($serial);
			$hardwareContructor->setStatus(Sss_Ultility_Setting::HARDWARE_STATUS_ACTIVE);
			$hardwareContructor->setAllocation($allocation);
			$hardwareContructor->setCreatedDate(Sss_Ultility_Common::getDateTimeNumber());
			$hardwareContructor->setUpdatedDate(Sss_Ultility_Common::getDateTimeNumber());
			$hardwareContructor->setValid(0);
			$hardwareContructor->setCreatedBy(1);
			$hardwareContructor->setUpdatedBy(1);
			$hardwareId = $hardwareTable->save($hardwareContructor);
			if (isset($hardwareId)) {
				//add inventory when add hardware successfull
				if ($stockLocation != -1) {
					$inventoryTable = new Application_Model_Mapper_Inventory();
					$inventoryContructor = new Application_Model_Inventory();
					$inventoryContructor->setStockLocation($stockLocation);
					$inventoryContructor->setHardware($hardwareId);
					$inventoryContructor->setIsactivated(1);
					$inventoryContructor->setFromDate(Sss_Ultility_Common::getDateTimeNumber());
					$inventoryContructor->setToDate(Sss_Ultility_Common::getDateTimeNumber());
					$inventoryContructor->setAssigneBy(1);
					$inventoryContructor->setStatus(Sss_Ultility_Setting::HARDWARE_STATUS_ACTIVE);
					$inventoryTable->save($inventoryContructor);
				}
			}
			return $hardwareId;
		}

		/**
		* Get  status of network in floor plan
		*  
		* @param array $arrNetwork
		* rerurn array $arrStatusNetwork
		*/
		public function getStatusNetwork($arrayNetwork)
		{
			foreach ( $arrayNetwork as $arrNetwork ) {
				$arrStatusNetwork = $arrNetwork;
				foreach ($arrNetwork as $key => $network) {
					foreach ($arrStatusNetwork as $i => $n) {
						if ($network[Sss_Ultility_CommonViewParamater::STATUS_NETWORK] && !$n[Sss_Ultility_CommonViewParamater::STATUS_NETWORK]
						&& $network['vendor'] == $n['vendor'] 
						&& $network['stocklocation'] == $n['stocklocation']){
							$network[Sss_Ultility_CommonViewParamater::STATUS_NETWORK] = false;
						}
						if ($network['vendor'] == $n['vendor'] 
						&& $network['stocklocation'] == $n['stocklocation']) {
							unset($arrStatusNetwork[$i]); 
						}
					}
					$arrStatusNetwork[$key] = $network;
				}
			}
			return $arrStatusNetwork;
		}

		/**
		* Get contact information of stock location in administration
		*
		* @param $stockLocation
		* rerurn object $inforStock
		*/
		public function getInforStockLocation($stockLocation)
		{
			$stockLocationTable = new Application_Model_Mapper_StockLocation();
			$inforStock = $stockLocationTable->select($stockLocation);
			if($inforStock == false) {
				return false;
			} else {
				return $inforStock;
			}
		}

		/**
		* Get list hardware of instance
		*
		* @param $limit,$limitstart,$filterParam,$instance
		* rerurn object $listHardware
		*/
		public function getListMyHardware($limit,$limitstart,$filterParam,$instance)
		{
			$hardwareTable = new Application_Model_Mapper_Hardware();;
			$listHardware = $hardwareTable->getListHardwareOfShepherd($instance,$limit,$limitstart,$filterParam);
			if(empty($listHardware->list)) { 
				return false;
			} else {
				return $listHardware;
			}
		}

		//function of Shepherd BI
		public function getWSDL()
		{
			$url = SERVICE_URL_SHEPHERDBI;
			global $loginconf;
			$wsdl = $loginconf['WS_DDR']['hostname'];
			if($loginconf['WS_DDR']['port'] != "") {
				$wsdl .= ":".$loginconf['WS_DDR']['port'];
			}
			$wsdl .= $loginconf['WS_DDR']['pentahodir'];
			$wsdl .= $url;
			return $wsdl;
		}

		public function connectShepherdBI()
		{
			$client = new SoapClient(
					self::getWSDL(),
					array(
							'style'    => SOAP_DOCUMENT,
							'use'      => SOAP_LITERAL
					)
			);
			return $client;
		}

		public static $extensions = array(
				"Pre-Defined Reports" => ".prpt",
				"Dashboards"          => ".xcdf"
		);

		public function getReportsByPath()
		{
			try {
				$client = self::connectShepherdBI();
				$res = $client->GetDDRRepositoryByPath(array("repositoryPath" => "/shepherd-bi/Reporting"));
			} catch (Exception $e) {
				self::logger()->log($e, Zend_Log::ERR);
				return false;
			}
			$rps = array();
			if(is_array($res->return)) {
				foreach ($res->return as $rp) {
					$rps[] = substr($rp, 0, (-1 * strlen(self::$extensions['Pre-Defined Reports'])));
				}
			} else {
				$rps[] = substr($res->return, 0, (-1 * strlen(self::$extensions['Pre-Defined Reports'])));
			}
			return $rps;
		}

		public function getDashBoardByPath()
		{
			try {
				$client = self::connectShepherdBI();
				$res = $client->GetDDRRepositoryByPath(array("repositoryPath" => "/shepherd-bi/Dashboards"));
			} catch (Exception $e) {
				self::logger()->log($e, Zend_Log::ERR);
				return false;
			}
			$rps = array();
			if(is_array($res->return)) {
				foreach ($res->return as $rp) {
					$rps[] = substr($rp, 0, (-1 * strlen(self::$extensions['Dashboards'])));
				}
			} else {
				$rps[] = substr($res->return, 0, (-1 * strlen(self::$extensions['Dashboards'])));
			}
			return $rps;
		}

		//save report of user
		public function SaveReport($username,$arrReport)
		{
			//get reports
			$DDR_Reports = array();
			if(count($arrReport) > 0) {
				foreach($arrReport as $rp) {
					$rd = new RoleDetail(0,0, $rp.self::$extensions['Pre-Defined Reports']);
					$DDR_Reports[] = $rd;
				}
			}
			//call web service
			try {
				$client = self::connectShepherdBI();
				$value = array(
						'virtualUserName' => $username,
						'drivingSchoolID' => 0,
						"repositoryPath" => "/shepherd-bi/Reporting",
						'lstRoles' => $DDR_Reports
				);
				$res = $client->GrantPermissionOnReportsByPath($value);
				return $res;
			} catch (Exception $e) {
				self::logger()->log($e, Zend_Log::ERR);
				return false;
			}
		}

		//save Dashboard of user
		public function SaveDashboard($username,$arrReport)
		{
			//get reports
			$DDR_Reports = array();
			if(count($arrReport) > 0) {
				foreach($arrReport as $rp) {
					$rd = new RoleDetail(0,0, $rp.self::$extensions['Dashboards']);
					$DDR_Reports[] = $rd;
				}
			}
			//call web service
			try {
				$client = self::connectShepherdBI();
				$value = array(
						'virtualUserName' => $username,
						'drivingSchoolID' => 0,
						"repositoryPath" => "/shepherd-bi/Dashboards",
						'lstRoles' => $DDR_Reports
				);
				$res = $client->GrantPermissionOnReportsByPath($value);
				return $res;
			} catch (Exception $e) {
				self::logger()->log($e, Zend_Log::ERR);
			}
		}

		public function grantPermissionData($user,$objectName,$shepherdKey)
		{
			try {
				$client = self::connectShepherdBI();
				$checkData = $client->checkPermissionDataExists(array("userName" => $user,
						"objectName" => $objectName, "shepherdKey" => $shepherdKey));
				if(!$checkData->return) {
					$client->grantPermissionData(array("userName" => $user,
						"objectName" => $objectName, "shepherdKey" => $shepherdKey));
				}
			} catch (Exception $e) {
				self::logger()->log($e, Zend_Log::ERR);
				return false;
			}
		}

		//Remove permission data
		public function removeUserPermissionData($user,$objectName,$shepherdKey)
		{
			try {
				$client = self::connectShepherdBI();
				$client->removePermissionData(array("userName" => $user,
						"objectName" => $objectName, "shepherdKey" => $shepherdKey));
			} catch (Exception $e) {
				self::logger()->log($e, Zend_Log::ERR);
				return false;
			}
		}

		public function removeUserPermissionReportUser($user, $file)
		{
			try {
				$client = self::connectShepherdBI();
				foreach ($file as $f) {
					$files[] = $f.self::$extensions['Pre-Defined Reports'];
				}
				$client->removeUserPermissionOnFilesByPath(array("userName" => $user,
						"repositoryPath" => "/shepherd-bi/Reporting", "lstFiles" => $files));
			} catch (Exception $e) {
				self::logger()->log($e, Zend_Log::ERR);
				return false;
			}
		}

		public function removeUserPermissionDashboardUser($user, $file)
		{
			try {
				$client = self::connectShepherdBI();
				foreach ($file as $f) {
					$files[] =  $f.self::$extensions['Dashboards'];
				}
				$client->removeUserPermissionOnFilesByPath(array("userName" => $user,
						"repositoryPath" => "/shepherd-bi/Dashboards", "lstFiles" => $files));
			} catch (Exception $e) {
				printf("Error: %s\n",$e->__toString());
				return false;
			}
		}

		public function addUserAndDashboard($user,$encryptedPassword,$fullName,$instance,$dataRole,$admin=null)
		{
			try { 
				$client = self::connectShepherdBI();
				$value = array(
						'virtualUserName'   => $user,
						'virtualPassword'   => $encryptedPassword,
						'realUserName'      => $fullName
				);
				$valueCheck = array(
						'virtualUserName'   => $user
				);
				$check = $client->ExistedUser($valueCheck);
				//add new user
				if($check->return == false) {
					$client->SaveOrUpdateUser($value);
				}
				//add dashboard and report of user
				if($dataRole != null || $admin == Sss_Ultility_CommonViewParamater::USER_NAME_SHEPHERD_DEFAULT) { 
					$arrReport = self::getReportsByPath();
					$arrDashBoard = self::getDashBoardByPath();
					//Save report
					self::SaveReport($user,$arrReport);
					//Save Dashboard
					self::SaveDashboard($user,$arrDashBoard);
					//Save permission report data
					foreach($arrReport  as $report) {
						self::grantPermissionData($user,$report,$instance);
					}
					//Save permission dashboards data
					foreach($arrDashBoard  as $dashboard) {
						self::grantPermissionData($user,$dashboard,$instance);
					}
				}
			} catch (Exception $e) {
				self::logger()->log($e, Zend_Log::ERR);
			}
		}

		public function removeDashboardAndRrport($user,$instance)
		{
			try {
				$arrReport = self::getReportsByPath();
				$arrDashBoard = self::getDashBoardByPath();
				//Remove report of user
				self::removeUserPermissionReportUser($user,$arrReport);
				//Remove dashboard of user
				self::removeUserPermissionDashboardUser($user,$arrDashBoard);
				//Remove permission report data
				foreach($arrReport  as $report) {
					self::removeUserPermissionData($user,$report,$instance);
				}
				//Remove permission dashboards data
				foreach($arrDashBoard  as $dashboard) {
					self::removeUserPermissionData($user,$dashboard,$instance);
				}
			} catch (Exception $e) {
				self::logger()->log($e, Zend_Log::ERR);
			}
		}

		public function deleteUserBi($user,$instance)
		{
			try {
				$client = self::connectShepherdBI();
				$valueCheck = array(
						'virtualUserName'   => $user
				);
				$check = $client->ExistedUser($valueCheck);
				if($check->return == true) {
					self::removeDashboardAndRrport($user,$instance);
					//delete user of shepherd BI
					$client->removeUser(array("userName" => $user));
				}
			} catch ( Exception $e ) {
				self::logger()->log($e, Zend_Log::ERR);
			}
		}

		public function updateUserBi($user,$activateCode,$fullname)
		{
			try {
				$client = self::connectShepherdBI();
				$value = array(
						'virtualUserName'   => $user,
						'virtualPassword'   => $activateCode,
						'realUserName'      => $fullname
				);
				$client->SaveOrUpdateUser($value);
			} catch ( Exception $e ) {
				self::logger()->log($e, Zend_Log::ERR);
			}
		}
		public function getPagination($limit, $limitstart, $orderField, $orderType, $page, $columnDefault = null,$nameTable = null)
		{
			//initializa order by
			$orderBy = '';
			if(is_null($orderField) && $columnDefault != null) {
				$orderField = $columnDefault;
			}
			if (!is_null($orderField)) {
				$typeOrder = !is_null($orderType) ? $orderType : 'ASC';
				$name = $nameTable != null ? $nameTable."." : "";
				$orderBy   = ' ORDER BY ' .$name. $orderField . ' ' . $typeOrder;
				if($orderField == 'stock') {
					$orderBy   = " ORDER BY ".Sss_Ultility_Setting::STOCK_ACTIVE." ".$typeOrder;
				}
			}

			//initializa pagination
			$pagString = '';
			if ($limit == '') {
				$limit = Sss_Ultility_Setting::PAGE_SIZE;
			}
			if ($page == null) {
				$limitstart = 0;
			} else {
				$limitstart = $limit * ($page - 1);
			}
			if ($limit < 0) {
				$pagString = '';
			} else {
				$pagString = ' LIMIT ' . $limitstart . ' , ' . $limit;
			}
			$arrPagination['orderby']    = $orderBy;
			$arrPagination['limit']      = $limit;
			$arrPagination['limitstart'] = $limitstart;
			$arrPagination['pagstring']  = $pagString;
			return $arrPagination;
		}

		function getColumnInPostData($v, $existedData, $dataId, $instanceId)
		{
			$arr = explode('_', $v);
			$cols = null;
			$arrData = array();
			$postDataTable = new Shepherd_Model_Mapper_PostData();
			if ($existedData && $dataId) {
				$postDataContructor = $postDataTable->findById($dataId, $instanceId);
			} else {
				$postDataContructor = new Shepherd_Model_PostData();
			}
			switch($arr[0]) {
				case 1:
					$cols = Sss_Ultility_CommonViewParamater::COLS_TEMPERATURE;
					$postDataContructor->setTemperature1($arr[2]);
					break;
				case 2:
					$cols = Sss_Ultility_CommonViewParamater::COLS_HUMIDITY;
					$postDataContructor->setRelativeHumidity($arr[2]);
					break;
				case 3:
					$cols = Sss_Ultility_CommonViewParamater::COLS_VOLTAGE;
					$postDataContructor->setBatteryVoltage($arr[2]);
					break;
				case 4:
					$cols = Sss_Ultility_CommonViewParamater::COLS_LIFE;
					$postDataContructor->setShelfLife($arr[2]);
					break;
				case 5:
					$cols = Sss_Ultility_CommonViewParamater::COLS_LIFELOSS;
					$postDataContructor->setDoSlLpd($arr[2]);
					break;
				case 6:
					$cols = Sss_Ultility_CommonViewParamater::COLS_TEMPERATUREPT100;
					$postDataContructor->setEtPt100($arr[2]);
					break;
				case 7:
					$cols = Sss_Ultility_CommonViewParamater::COLS_PRESSURE;
					$postDataContructor->setAirPressure($arr[2]);
					break;
				case 8:
					$cols = Sss_Ultility_CommonViewParamater::COLS_SHOCK;
					$postDataContructor->setShock($arr[2]);
					break;
				case 9:
					$cols = Sss_Ultility_CommonViewParamater::COLS_FREEFALL;
					$postDataContructor->setFreeFall($arr[2]);
					break;
				case 10:
					$cols = Sss_Ultility_CommonViewParamater::COLS_INSTENSITY;
					$postDataContructor->setLightIntensity($arr[2]);
					break;
				case 11:
					$cols = Sss_Ultility_CommonViewParamater::COLS_HEADING;
					$postDataContructor->setHeading($arr[2]);
					break;
				case 12:
					$cols = Sss_Ultility_CommonViewParamater::COLS_CO2;
					$postDataContructor->setCo2($arr[2]);
					break;
				case 13:
					$cols = Sss_Ultility_CommonViewParamater::COLS_CONTACT;
					$postDataContructor->setContact($arr[2]);
					break;
			}
			$arrData['cols'] = $cols;
			$arrData['postdata'] = $postDataContructor;
			return $arrData;
		}
		function checkCreateColumn($instanceid)
		{
			$postDataTable = new Shepherd_Model_Mapper_PostData();
			$postDataTable->checkEsixtedColumns(Sss_Ultility_CommonViewParamater::COLS_TEMPERATURE, $instanceid);
			$postDataTable->checkEsixtedColumns(Sss_Ultility_CommonViewParamater::COLS_HUMIDITY, $instanceid);
			$postDataTable->checkEsixtedColumns(Sss_Ultility_CommonViewParamater::COLS_VOLTAGE, $instanceid);
			$postDataTable->checkEsixtedColumns(Sss_Ultility_CommonViewParamater::COLS_LIFE, $instanceid);
			$postDataTable->checkEsixtedColumns(Sss_Ultility_CommonViewParamater::COLS_LIFELOSS, $instanceid);
			$postDataTable->checkEsixtedColumns(Sss_Ultility_CommonViewParamater::COLS_TEMPERATUREPT100, $instanceid);
			$postDataTable->checkEsixtedColumns(Sss_Ultility_CommonViewParamater::COLS_PRESSURE, $instanceid);
			$postDataTable->checkEsixtedColumns(Sss_Ultility_CommonViewParamater::COLS_SHOCK, $instanceid);
			$postDataTable->checkEsixtedColumns(Sss_Ultility_CommonViewParamater::COLS_FREEFALL, $instanceid);
			$postDataTable->checkEsixtedColumns(Sss_Ultility_CommonViewParamater::COLS_INSTENSITY, $instanceid);
			$postDataTable->checkEsixtedColumns(Sss_Ultility_CommonViewParamater::COLS_HEADING, $instanceid);
			$postDataTable->checkEsixtedColumns(Sss_Ultility_CommonViewParamater::COLS_CO2, $instanceid);
			$postDataTable->checkEsixtedColumns(Sss_Ultility_CommonViewParamater::COLS_CONTACT, $instanceid);
			$postDataTable->checkEsixtedColumns(Sss_Ultility_CommonViewParamater::COLS_LAT, $instanceid);
			$postDataTable->checkEsixtedColumns(Sss_Ultility_CommonViewParamater::COLS_LONG, $instanceid);
			$postDataTable->checkEsixtedColumns(Sss_Ultility_CommonViewParamater::COLS_POS_TYPE, $instanceid);
			$postDataTable->checkEsixtedColumns(Sss_Ultility_CommonViewParamater::COLS_ERROR, $instanceid);
			$postDataTable->checkEsixtedColumns(Sss_Ultility_CommonViewParamater::COLS_SPEED, $instanceid);
			$postDataTable->checkEsixtedColumns(Sss_Ultility_CommonViewParamater::COLS_HEADING, $instanceid);
		}
		function processSavePostData($isUpdate = false, $params = null, $isPos = true, $arr = null)
		{
			$postDataTable = new Shepherd_Model_Mapper_PostData();
			if ($isPos) {
				if ($isUpdate) {
					$dataId = $postDataTable->getIdByData($params['hardwareid'], $params['createddate'], $params['sitename'], $params['instanceid']);
					$arrPostData = Sss_Ultility_Common::getColumnInPostData($params['v'], $params['existeddata'], $dataId->dataid, $params['instanceid']);
					$dataId = $postDataTable->save($arrPostData['postdata'],  $params['instanceid']);
				} else {
					$params['postdata']->setSiteName($params['sitename']);
					$params['postdata']->setHardware($params['hardwareid']);
					$params['postdata']->setCreatedDate($params['createddate']);
					$dataId = $postDataTable->save($params['postdata'], $params['instanceid']);
				}
			} else {
				if ($isUpdate) {
					$dataId = $postDataTable->getIdByData($params['hardwareid'], $params['createddate'], $params['sitename'], $params['instanceid']);
					$postData = $postDataTable->findById($dataId->dataid, $params['instanceid']);
					$postData->setPosType(trim($arr[3]));
					$postData->setLatValue(trim($arr[4]));
					$postData->setLongValue(trim($arr[5]));
					$postData->setError(trim($arr[6]));
					$postData->setSpeed(trim($arr[7]));
					$postData->setHeading(trim($arr[8]));
					$dataId = $postDataTable->save($postData, $params['instanceid']);
				} else {
					$postData = new Shepherd_Model_PostData();
					$postData->setHardware($params['hardwareid']);
					$postData->setCreatedDate($params['createddate']);
					$postData->setSiteName($params['sitename']);
					$postData->setPosType(trim($arr[3]));
					$postData->setLatValue(trim($arr[4]));
					$postData->setLongValue(trim($arr[5]));
					$postData->setError(trim($arr[6]));
					$postData->setSpeed(trim($arr[7]));
					$postData->setHeading(trim($arr[8]));
					$dataId = $postDataTable->save($postData, $params['instanceid']);
				}
			}
			return $dataId;
		}
	}

	class RoleDetail {
		public $shepherdID ;
		public $roleID ;
		public $reportName;
	
		function __construct($subid, $roleid, $reportname) {
			$this->shepherdID = $subid;
			$this->roleID       = $roleid;
			$this->reportName   = $reportname;
		}
	}

